﻿/**
 * jQuery EasyUI 1.4
 *
 * Copyright (c) 2009-2014 www.jeasyui.com. All rights reserved.
 *
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt To use it
 * on other terms please contact us at info@jeasyui.com
 *
 */
(function($) {
	//必须保证两条数据下标是相等的。
	function deleteObject(array,questionObjs,id) {
		if(array && array instanceof Array){
			for (var i = 0, len = array.length; i < len; i++) {
				if (array[i] == id) {
					array.splice(i, 1);
					questionObjs.splice(i, 1);
					return;
				}
			}
		}
	};
	function exchangePosition(array,questionObjs,id,isUpOrDown) {
		if(array && array instanceof Array){
			for (var i = 0, len = array.length; i < len; i++) {
				if (array[i] == id) {
					if(isUpOrDown){
						if(i-1>=0){
							var dq=array[i-1];
							var qObj=questionObjs[i];
							var dqObj=questionObjs[i-1];
							array.splice(i-1, 2,id,dq);
							questionObjs.splice(i-1, 2,qObj,dqObj);
						}
					}else{
						if(i+1<len){
							var dq=array[i+1];
							var qObj=questionObjs[i];
							var dqObj=questionObjs[i+1];
							array.splice(i, 2,id,dq);
							questionObjs.splice(i, 2,dqObj,qObj);
						}
					}
					return;
				}
			}
		}
	};

	function createTest(target){
		var testBox = $.data(target, "testBox");
		var body=$("<div class=\"testBox-body\"></div>");
		body.prependTo($(target));
		testBox.body=body;
	}


	function createQuestion(target,queObj,isEnd){
		var testBox = $.data(target, "testBox");
		var opts = testBox.options;
		var darg=$("<div></div>");
		if(isEnd){
			testBox.body.prepend(darg);
		}else{
			testBox.body.append(darg);
		}
		var question=null;
		if(queObj.isNew==false){
			question=queObj;

			if(opts.showScore){
				queObj.showScore=opts.showScore;
			}
			if(opts.score){
				queObj.score=opts.score;
			}
		}else if(queObj.questionId){
			var isADisplay=false;
			if(queObj.isADisplay && queObj.isADisplay==true){
				isADisplay=true;
			}
			var showScore=false;
			if(queObj.showScore){
				showScore=true;
			}else{
				if(opts.showScore){
					showScore=opts.showScore;
				}
			}
			var score=0;
			if(queObj.score){
				score=queObj.score;
			}else{
				if(opts.score){
					score=opts.score;
				}
			}
			question={
				id:queObj.questionId,
				isNew:true,
				title:queObj.title,
				context:"题干内容",
				shortAnswer:"",
				categoryItemId:null,
				type:queObj.type,
				showScore:showScore,
				score:score,
				isADisplay:isADisplay
			};
		}else{
			var isADisplay=false;
			if(queObj.isADisplay && queObj.isADisplay==true){
				isADisplay=true;
			}
			var showScore=false;
			if(queObj.showScore){
				showScore=true;
			}else{
				if(opts.showScore){
					showScore=opts.showScore;
				}
			}
			var score=0;
			if(queObj.score){
				score=queObj.score;
			}else{
				if(opts.score){
					score=opts.score;
				}
			}
			question={
				isNew:true,
				title:queObj.title,
				context:"题干内容",
				shortAnswer:"",
				categoryItemId:null,
				type:queObj.type,
				showScore:showScore,
				score:score,
				isADisplay:isADisplay,
				status:queObj.status||"edit-sleep"
			};
		}

		var questionObj=null;
		if(queObj.type==1){
			questionObj=darg.judgmentQuestion({
				title:queObj.title,
				testBox:target,
				type:queObj.type,
				question:question,
				status:queObj.status||"edit-sleep"
			});

		}else if(queObj.type==2){
			questionObj=darg.choiceQuestion({
				title:queObj.title,
				testBox:target,
				isMultiple:false,
				type:queObj.type,
				question:question,
				status:queObj.status||"edit-sleep"
			});
		}else if(queObj.type==3){
			questionObj=darg.choiceQuestion({
				title:queObj.title,
				testBox:target,
				isMultiple:true,
				type:queObj.type,
				question:question,
				status:queObj.status||"edit-sleep"
			});
		}else if(queObj.type==4){
			questionObj=darg.blanksQuestion({
				title:queObj.title,
				testBox:target,
				isMultiple:true,
				type:queObj.type,
				question:question,
				status:queObj.status||"edit-sleep",
				onCountFullMarks : function(queObj){},
			});
		}else if(queObj.type==8){
			questionObj=darg.lineQuestion({
				title:queObj.title,
				testBox:target,
				isMultiple:true,
				type:queObj.type,
				question:question,
				status:queObj.status||"edit-sleep"
			});
		}else if(queObj.type==9){
			questionObj=darg.sortQuestion({
				title:queObj.title,
				testBox:target,
				isMultiple:true,
				type:queObj.type,
				question:question,
				status:queObj.status||"edit-sleep"
			});
		}else if(queObj.type==10){
			questionObj=darg.shortQuestion({
				title:queObj.title,
				testBox:target,
				isMultiple:true,
				type:queObj.type,
				question:question,
				status:queObj.status||"edit-sleep"
			});
		}else if(queObj.type==11){
			questionObj=darg.correctionsQuestion({
				title:queObj.title,
				testBox:target,
				isMultiple:true,
				type:queObj.type,
				question:question,
				status:queObj.status||"edit-sleep"
			});
		}else{
			alert("没有试题类型");
			return;
		}
		questionObj.parent().bind("mousedown",function(){
			if(opts.currentQuestion==questionObj){
				return;
			}
			if(opts.currentQuestion){
				opts.currentQuestion.qtiBox("setSleep");
			}
			questionObj.qtiBox("setEdit");
			opts.currentQuestion=questionObj;
		});
		var question=questionObj.qtiBox("options").question;
		if(isEnd){
			opts.questionObjs.unshift(questionObj);
			//设置内容
			opts.questions.unshift(question);
		}else{
			opts.questionObjs.push(questionObj);
			//设置内容
			opts.questions.push(question);
		}

		opts.currentQuestion=questionObj;

	}


	function renderTestBoxLoadData(target, data) {
		var testBox = $.data(target, "testBox");
		var opts = testBox.options;
		data = opts.loadFilter.call(target, data);

		for(var i=0;i<data.questions.length;i++){
			createQuestion(target, data.questions[i]);
		}
		//把其他试题，改为未选中
		if(opts.currentQuestion){
			opts.currentQuestion.qtiBox("setEdit");
		}
		for(var n=0;n<opts.questionObjs.length;n++){
			opts.questionObjs[n].qtiBox("resize");
		}
	}

	function request(target, param) {
		var opts = $.data(target, "testBox").options;
		if (param) {
			opts.queryParams = param;
		}
		var optsQueryParams=opts.queryParams;
		if(typeof(opts.queryParams)=="function"){
			optsQueryParams=opts.queryParams();
		}
		var queryParams={};
		if(optsQueryParams){
			if(typeof(optsQueryParams)=="object"){
				queryParams=$.extend({},optsQueryParams);
			}else{
				//如果，使用字符串作为参数的话，就无法使用分页功能，那么分页功能必须作为字符串的形式传入
				queryParams=optsQueryParams;
			}
		}

		if (opts.onBeforeLoad.call(target, queryParams) == false) {
			return;
		}
		$(target).testBox("loading");
		setTimeout(function() {_loaderData();}, 0);
		function _loaderData() {
			var _bool = opts.loader.call(target, queryParams, function(data) {
				setTimeout(function() {$(target).testBox("loaded");}, 0);
				renderTestBoxLoadData(target, data);
				opts.onLoadSuccess.apply(target, data);
			}, function() {
				setTimeout(function() {$(target).testBox("loaded");}, 0);
				opts.onLoadError.apply(target, arguments);
			});
			if (_bool == false) {
				$(target).testBox("loaded");
			}
		};
	};


	$.fn.testBox = function(method, options) {
		if (typeof method == "string") {
			return $.fn.testBox.methods[method](this, options);
		}
		method = method || {};
		return this.each(function() {
			var testBox = $.data(this, "testBox");
			var opts;
			if (testBox) {
				opts = $.extend(testBox.options, method);
				testBox.isLoaded = false;
			} else {
				opts = $.extend({}, $.fn.testBox.defaults, $.fn.testBox.parseOptions(this), method);
				opts.questionObjs=[],
				opts.questions=[],
				$(this).attr("title", "");
				$.data(this, "testBox",{
					options : opts
				});
			}
			createTest(this);
			if(opts.url){
				request(this);
			}else if(opts.data){
				renderTestBoxLoadData(this, opts.data);
			}
		});
	};
	$.fn.testBox.methods = {
		options : function(jq) {
			return $.data(jq[0], "testBox").options;
		},
		createQuestion:function(jq,queObj){
			return jq.each(function() {
				var opts = $.data(this, "testBox").options;
				queObj.status="edit-question";
				//把其他试题，改为未选中
				if(opts.currentQuestion){
					opts.currentQuestion.qtiBox("setSleep");
				}
				createQuestion(this, queObj,queObj.isEnd);
			});
		},
		setCurrentQuestion:function(jq,question){
			return jq.each(function() {
				$.data(this, "testBox").options.currentQuestion=question;
			});
		},
		removeQuestion:function(jq,question){
			return jq.each(function() {
				var questions=$.data(this, "testBox").options.questions;
				var questionObjs=$.data(this, "testBox").options.questionObjs;
				deleteObject(questions,questionObjs,question);
			});
		},
		exchangeUp:function(jq,question){
			return jq.each(function() {
				var questions=$.data(this, "testBox").options.questions;
				var questionObjs=$.data(this, "testBox").options.questionObjs;
				exchangePosition(questions,questionObjs,question,true);
			});
		},
		exchangeDown:function(jq,question){
			return jq.each(function() {
				var questions=$.data(this, "testBox").options.questions;
				var questionObjs=$.data(this, "testBox").options.questionObjs;
				exchangePosition(questions,questionObjs,question,false);
			});
		},
		addLoad : function(jq,param) {
			return jq.each(function() {
				var opts = $.data(this, "testBox").options;
				if (typeof param == "string") {
					opts.url = param;
					param = null;
				}
				if(param.url){
					opts.url = param.url;
					param=param.queryParams;
				}
				request(this,param);
			});
		},
		loading : function(jq) {
			return jq.each(function() {
				var opts = $.data(this, "testBox").options;
				if (opts.loadMsg) {
					var panel = $(this);
					$("<div class=\"testBox-mask\" style=\"display:block\"></div>").appendTo(panel);
					var msg = $("<div class=\"testBox-mask-msg\" style=\"left:50%\"></div>").html(opts.loadMsg).appendTo(panel);
					msg._outerHeight(40);
					msg.css({
						marginLeft : (-msg.outerWidth() / 2),
						lineHeight : (msg.height() + "px")
					});
				}
			});
		},
		loaded : function(jq) {
			return jq.each(function() {
				$(this).children("div.testBox-mask-msg").remove();
				$(this).children("div.testBox-mask").remove();
			});
		},

		toJson:function(jq){
			var opts=$.data(jq[0], "testBox").options;
			var questionArray=[];

			for(var n=0;n<opts.questionObjs.length;n++){
				var qtiOpts=opts.questionObjs[n].qtiBox("options");
				//判断当前是否为答案状态，如果是答案状态，需要重新获取一下答案内容。
				if(qtiOpts && qtiOpts.status=="edit-answer"){
					opts.questionObjs[n].qtiBox("calculationAnswer");
				}
//				//重新计算一次答案，
//				//并且验证，是否有没有按照条件计算的试题
			}
			for(var i=0;i<opts.questions.length;i++){
				var old=opts.questions[i];
				var isADisplay=false;
				if(old.isADisplay==true){
					isADisplay=true;
				}
				var score=0;
				if(old.score && old.score>=0){
					score=old.score;
				}
				var lineAnswer=new Array();
				if(old.type==8){
					for(var liIndex=0; old.lineAnswer && liIndex<old.lineAnswer.length;liIndex++){
						var leftAnswer=old.lineAnswer[liIndex].leftAnswer;
						if(!leftAnswer){
							$.messager.show({
								title:"消息提示",
								msg:"连线题答案必须填写完整",
								showType:"slide",
								timeout:2000,
								style:{
									right:'',
									top:document.body.scrollTop+document.documentElement.scrollTop,
									bottom:''
								}
							},"error");
							return "";
						}
						var rigthAnswer=old.lineAnswer[liIndex].rigthAnswer;
						if(!rigthAnswer){
							$.messager.show({
								title:"消息提示",
								msg:"连线题答案必须填写完整",
								showType:"slide",
								timeout:2000,
								style:{
									right:'',
									top:document.body.scrollTop+document.documentElement.scrollTop,
									bottom:''
								}
							},"error");
						}
						lineAnswer.push({
							left:leftAnswer.sortContext,
							right:rigthAnswer.sortContext
						});
					}
				}
				var sortQuestionsAnswer="";
				if(old.type==9){
					sortQuestionsAnswer=old.sortQuestionsAnswer;
				}
				var newQue={
					id:old.id,
					isNew:old.isNew,
					title:old.title,
					difficulty:old.difficulty,
					context:old.contextObj.html(),
					candidateAnswer:[],
					type:old.type,
					lineAnswer:lineAnswer,
					sortQuestionsAnswer:sortQuestionsAnswer,
					shortAnswer:old.shortAnswer,
					isADisplay:isADisplay,
					score:score,

				};
				for(var n=0;n<old.candidateAnswer.length;n++){
					//设置选项内容
					var  anContext="";
					if(old.type==11 || old.type==4){
						anContext="";
					}else if(old.type==4){
						anContext=old.candidateAnswer[n].context;
					}else{
						anContext=old.candidateAnswer[n].contextObj.html();
					}

					var sortContext="";
					if(old.candidateAnswer[n].sortContext){
						sortContext=old.candidateAnswer[n].sortContext;
					}

					var optionAnswer=new Array();
					if(old.candidateAnswer[n].optionAnswer){
						optionAnswer=old.candidateAnswer[n].optionAnswer;
					}
					var answer={
						id:old.candidateAnswer[n].id,
						isNew:old.candidateAnswer[n].isNew,
						context:anContext,
						sortContext:sortContext,
						optionAnswer:optionAnswer,
						isCorrectAnswer:old.candidateAnswer[n].isCorrectAnswer,
					};
					newQue.candidateAnswer.push(answer);
				}
				questionArray.push(newQue);
			}
			return questionArray;
		},
	};
	$.fn.testBox.parseOptions = function(target) {return {};};
	$.fn.testBox.defaults = {
		id : null,
		url : null,
		data : null,
		//两种模式，编辑模式，考试模式
		model:"edit",
		method:"post",
		body:null,
		loader : function(param, successCall, errorCall) {
			var opts = $(this).testBox("options");
			if (!opts.url) {
				return false;
			}
			$.ajax({
				type : opts.method,
				url : opts.url,
				data : param,
				dataType : "json",
				success: function (data) {
					if (jQuery.isArray(data)) {
						successCall(data);
					} else if (data.status) {
						successCall(data.content);
					} else {
						$.messager.show({
							title: "消息提示",
							msg: data.message || "加载数据异常",
							showType: "slide",
							style: {
								right: '',
								top: document.body.scrollTop + document.documentElement.scrollTop,
								bottom: ''
							}
						}, "error");
						errorCall.apply(this, arguments);
					}
				},
				error : function() {
					errorCall.apply(this, arguments);
				}
			});
		},
		loadFilter : function(data) {
			if (typeof data.length == "number" && typeof data.splice == "function") {
				return {
					total : data.length,
					questions : data,
					model:"update"
				};
			} else {
				return data;
			}
		},
		onBeforeLoad : function(_24b) {
		},
		onLoadSuccess : function() {
		},
		onLoadError : function() {
		},
		onCountFullMarks : function(question){},
		onReduceFullMarks : function(question){},
		onCountBlanksAndLineMarks : function(question,oper){},
		loadMsg : "\u52A0\u8F7D\u8BD5\u9898, \u8BF7\u7A0D\u7B49...",
		queryParams : {},
		showScore:false,
		score:0,
		currentQuestion:null,
		questionObjs:null,
		questions:null,
	};
})(jQuery);
